package com.yisu.expressway.onedollar.activity;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.kyleduo.switchbutton.SwitchButton;
import com.yisu.expressway.R;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.onedollar.model.AddressObj;
import com.yisu.expressway.onedollar.model.UserAddressItem;
import com.yisu.expressway.onedollar.widget.DownUpPopupWindow;
import com.yisu.expressway.onedollar.widget.TitleView;
import com.yisu.expressway.onedollar.widget.addressselector.AddressProvider;
import com.yisu.expressway.onedollar.widget.addressselector.AddressSelector;
import com.yisu.expressway.onedollar.widget.addressselector.OnAddressSelectedListener;
import com.yisu.expressway.onedollar.widget.addressselector.model.City;
import com.yisu.expressway.onedollar.widget.addressselector.model.County;
import com.yisu.expressway.onedollar.widget.addressselector.model.Province;
import com.yisu.expressway.onedollar.widget.addressselector.model.Street;
import com.yisu.expressway.ui.MultiButtonDialog;
import com.yisu.expressway.utils.HBLog;
import com.yisu.expressway.utils.ToastUtil;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Kaven on 2016/12/20.
 */

public class UserAddressBuildActivity extends BasicActivity {
    public static final int BUILD_TYPE_INSERT = 1;
    public static final int BUILD_TYPE_UPDATE = 2;
    public static final String EXTRA_KEY_RESULT = "extra_key_result";
    public static final String EXTRA_KEY_RESULT_ORDER_ID = "extra_key_result_order_id";
    private static final String EXTRA_KEY_BUILD_TYPE = "extra_key_build_type";
    private static final String EXTRA_KEY_ADDRESS = "extra_key_address";
    private static final String EXTRA_KEY_MUST_DEFAULT = "extra_key_must_default";
    private static final String EXTRA_KEY_ORDER_ID = "extra_key_order_id";
    private static final String TAG = UserAddressBuildActivity.class.getSimpleName();
    @Bind(R.id.title_bar)
    protected TitleView mTitleView;
    @Bind(R.id.et_consignee_name)
    protected EditText mConsigneeNameEt;
    @Bind(R.id.et_consignee_phone)
    protected EditText mConsigneePhoneEt;
    @Bind(R.id.tv_area)
    protected TextView mAreaTv;
    @Bind(R.id.et_address)
    protected EditText mAddressEt;
    @Bind(R.id.sw_default)
    protected SwitchButton mDefaultSw;
    private DownUpPopupWindow mDownUpPopupWindow;
    private CustomAddressProvider addressProvider = new CustomAddressProvider();
    private int mBuildType = BUILD_TYPE_INSERT;
    private boolean bMustDefault = false;
    private long mOrderId;
    private UserAddressItem mUserAddressItem = new UserAddressItem();

    public static void launch(Activity context, int requestCode, UserAddressItem addressItem,
                              boolean mustDefault, long orderId) {
        Intent intent = new Intent(context, UserAddressBuildActivity.class);
        intent.putExtra(EXTRA_KEY_BUILD_TYPE, requestCode);
        intent.putExtra(EXTRA_KEY_ADDRESS, addressItem);
        intent.putExtra(EXTRA_KEY_ORDER_ID, orderId);
        intent.putExtra(EXTRA_KEY_MUST_DEFAULT, mustDefault);
        context.startActivityForResult(intent, requestCode);
    }

    @OnClick({ R.id.ll_area, R.id.tv_new })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_area:
                showPopDlg();
                break;
            case R.id.tv_new:
                mUserAddressItem.consigneeName = mConsigneeNameEt.getText().toString();
                mUserAddressItem.consigneePhone = mConsigneePhoneEt.getText().toString();
                mUserAddressItem.address = mAddressEt.getText().toString();
                mUserAddressItem.isDefault = mDefaultSw.isChecked() ? 1 : 0;
                if (mBuildType == BUILD_TYPE_INSERT) {
                    insertUserAddress(mUserAddressItem);
                } else {
                    updateUserAddress(mUserAddressItem);
                }

                break;
            default:
                break;
        }
    }

    private void insertUserAddress(final UserAddressItem item) {
        if (item == null) {
            return;
        }
        if (!TextUtils.isEmpty(mUserAddressItem.consigneeName)
                && !TextUtils.isEmpty(mUserAddressItem.consigneePhone)
                && !TextUtils.isEmpty(mUserAddressItem.address)) {
            Map<String, Object> params = new HashMap();

            params.put("address", item.address);
            params.put("area", item.area);
            params.put("city", item.city);
            params.put("consigneeName", item.consigneeName);
            params.put("consigneePhone", item.consigneePhone);
            params.put("isDefault", item.isDefault);
            params.put("province", item.province);
            ApiClientHelper.postApi(ApiSetting.insertUserAddress(), new TypeToken<Object>() {
            }, new JSONObject(params), new Response.Listener<ApiResult<Object>>() {
                @Override
                public void onResponse(ApiResult<Object> result) {
                    if (!result.success) {
                        ToastUtil.showMessage(UserAddressBuildActivity.this,
                                getString(R.string.one_dollar_user_address_insert_failed));
                    }
                    ToastUtil.showMessage(UserAddressBuildActivity.this,
                            getString(R.string.one_dollar_user_address_insert_suc));
                    Intent intent = new Intent();
                    intent.putExtra(EXTRA_KEY_RESULT, item);
                    if (mOrderId > 0) {
                        intent.putExtra(EXTRA_KEY_RESULT_ORDER_ID, mOrderId);
                    }

                    setResult(RESULT_OK, intent);
                    finishSelf(false);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    ToastUtil.showMessage(UserAddressBuildActivity.this,
                            getString(R.string.one_dollar_user_address_insert_failed));
                }
            }, this);

        } else {
            ToastUtil.showMessage(this, getString(R.string.one_dollar_user_address_input_warning));
        }
    }

    private void updateUserAddress(final UserAddressItem item) {
        if (item == null) {
            return;
        }
        if (!TextUtils.isEmpty(mUserAddressItem.consigneeName)
                && !TextUtils.isEmpty(mUserAddressItem.consigneePhone)
                && !TextUtils.isEmpty(mUserAddressItem.address)) {
            Map<String, Object> params = new HashMap();

            params.put("address", item.address);
            params.put("area", item.area);
            params.put("city", item.city);
            params.put("consigneeName", item.consigneeName);
            params.put("consigneePhone", item.consigneePhone);
            params.put("isDefault", item.isDefault);
            params.put("province", item.province);
            params.put("recordId", item.recordId);
            ApiClientHelper.postApi(ApiSetting.updateUserAddress(), new TypeToken<Object>() {
            }, new JSONObject(params), new Response.Listener<ApiResult<Object>>() {
                @Override
                public void onResponse(ApiResult<Object> result) {
                    if (!result.success) {
                        ToastUtil.showMessage(UserAddressBuildActivity.this,
                                getString(R.string.one_dollar_user_address_modify_failed));
                    }
                    ToastUtil.showMessage(UserAddressBuildActivity.this,
                            getString(R.string.one_dollar_user_address_modify_suc));
                    Intent intent = new Intent();
                    intent.putExtra(EXTRA_KEY_RESULT, item);
                    if (mOrderId > 0) {
                        intent.putExtra(EXTRA_KEY_RESULT_ORDER_ID, mOrderId);
                    }
                    setResult(RESULT_OK);
                    finishSelf(false);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    ToastUtil.showMessage(UserAddressBuildActivity.this,
                            getString(R.string.one_dollar_user_address_modify_failed));
                }
            }, this);

        } else {
            ToastUtil.showMessage(this, "请输入必要信息！");
        }
    }

    private void showPopDlg() {
        if (mDownUpPopupWindow == null) {
            AddressSelector selector = new AddressSelector(this, addressProvider);
            selector.setOnAddressSelectedListener(new OnAddressSelectedListener() {
                @Override
                public void onAddressSelected(Province province, City city, County county,
                                              Street street) {
                    HBLog.i(TAG, "<Province>     " + province.areaName);
                    HBLog.i(TAG, "<City>     " + city.areaName);
                    HBLog.i(TAG, "<County>       " + county.areaName);
                    mUserAddressItem.province = province.areaName;
                    mUserAddressItem.city = city.areaName;
                    mUserAddressItem.area = county.areaName;
                    mUserAddressItem.consigneeName = mConsigneeNameEt.getText().toString();
                    mUserAddressItem.consigneePhone = mConsigneePhoneEt.getText().toString();
                    mUserAddressItem.address = mAddressEt.getText().toString();
                    mUserAddressItem.isDefault = mDefaultSw.isChecked() ? 1 : 0;
                    setAddressViews();
                }
            });

            View view = selector.getView();

            mDownUpPopupWindow = new DownUpPopupWindow(this, view);
        }
        mDownUpPopupWindow.showAtLocation(mTitleView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0,
                0);

    }

    public void dismissPopDlg() {
        if (mDownUpPopupWindow != null && mDownUpPopupWindow.isShowing()) {
            mDownUpPopupWindow.dismiss();
            mDownUpPopupWindow = null;
        }
    }

    @Override
    protected int getThemeId() {
        return R.style.OneDollarTheme;
    }

    @Override
    protected int getInflateLayoutId() {
        return R.layout.onedollar_user_address_build;
    }

    @Override
    protected void initPresenter() {

    }

    @Override
    protected void releasePresenter() {

    }

    @Override
    protected void getIntentData(Intent intent) {
        int intExtra = intent.getIntExtra(EXTRA_KEY_BUILD_TYPE, -1);

        if (intExtra < 0) {
            finish();
            return;
        }
        mBuildType = intExtra;
        switch (intExtra) {
            case BUILD_TYPE_INSERT:
                break;
            case BUILD_TYPE_UPDATE:
                Serializable serializableExtra = intent.getSerializableExtra(EXTRA_KEY_ADDRESS);
                if (serializableExtra == null) {
                    finish();
                }
                mUserAddressItem = (UserAddressItem) serializableExtra;
                break;
            default:
                finish();
                break;
        }
        bMustDefault = intent.getBooleanExtra(EXTRA_KEY_MUST_DEFAULT, false);
        mOrderId = intent.getLongExtra(EXTRA_KEY_ORDER_ID, -1);
    }

    @Override
    protected void getSavedBundleData(Bundle bundle) {

    }

    @Override
    protected void initViews() {

        setAddressViews();

    }

    private void setAddressViews() {
        if (mUserAddressItem != null) {
            mConsigneeNameEt.setText(mUserAddressItem.consigneeName);
            mConsigneePhoneEt.setText(mUserAddressItem.consigneePhone);
            mAreaTv.setText(mUserAddressItem.toAreaString());
            mAddressEt.setText(mUserAddressItem.address);
            mDefaultSw.setChecked(bMustDefault ? true : mUserAddressItem.isDefault == 1);
            mDefaultSw.setEnabled(bMustDefault ? false : true);
        } else {
            mDefaultSw.setChecked(false);
        }
    }

    private void getAddressList(int parentId, int areaType,
                                Response.Listener<ApiResult<AddressObj>> listener) {
        Map<String, Object> params = new HashMap();

        params.put("parentid", parentId);
        params.put("areatype", areaType);
        ApiClientHelper.postApi(ApiSetting.getCountryAreaForLinkage(), new TypeToken<AddressObj>() {
        }, new JSONObject(params), listener, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }, this);
    }

    @Override
    protected void bindEvents() {
        mTitleView.setOnTitleBarClickEvent(new TitleView.OnTitleBarClickEvent() {
            @Override
            public void onLeftClick(View view) {
                finishSelf(true);
            }

            @Override
            public void onTitleClick(View view) {

            }

            @Override
            public void onRightClick(View view) {

            }
        });
        mDefaultSw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                mUserAddressItem.isDefault = b ? 1 : 0;
            }
        });
    }

    @Override
    protected boolean isNeedLogin() {
        return true;
    }

    @Override
    protected void onLoginStateChange(boolean login) {

    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finishSelf(true);
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private void finishSelf(boolean bShowDlg) {
        if (!bShowDlg) {
            finish();
            return;
        }
        if (!TextUtils.isEmpty(mConsigneeNameEt.getText())
                || !TextUtils.isEmpty(mConsigneePhoneEt.getText())
                || !TextUtils.isEmpty(mAddressEt.getText())
                || !TextUtils.isEmpty(mAreaTv.getText())) {
            showQuitWarningDlg();
        } else {
            finish();
        }
    }

    private void showQuitWarningDlg() {
        final MultiButtonDialog multiButtonDialog = new MultiButtonDialog(
                UserAddressBuildActivity.this);
        multiButtonDialog.show();
        multiButtonDialog.setButtonColor(R.color.oneDollarCommon);
        multiButtonDialog.setContentText(R.string.one_dollar_user_address_quit_warning);
        multiButtonDialog.setPositiveClickListener(new MultiButtonDialog.PositiveClickListener() {
            @Override
            public void onPositiveClick(String inputContent) {
                multiButtonDialog.dismiss();
                finish();
            }
        });
        multiButtonDialog.setNegativeClickListener(new MultiButtonDialog.NegativeClickListener() {
            @Override
            public void onNegativeClick(String inputContent) {
                multiButtonDialog.dismiss();
                finish();
            }
        });
    }

    class CustomAddressProvider implements AddressProvider {
        @Override
        public void provideProvinces(final AddressReceiver<Province> addressReceiver) {
            getAddressList(1, 0, new Response.Listener<ApiResult<AddressObj>>() {
                @Override
                public void onResponse(ApiResult<AddressObj> addressObjApiResult) {
                    addressReceiver.send(addressObjApiResult.getResult().provinceAssemble);
                }
            });

        }

        @Override
        public void provideCitiesWith(int provinceId, final AddressReceiver<City> addressReceiver) {
            getAddressList(provinceId, 1, new Response.Listener<ApiResult<AddressObj>>() {
                @Override
                public void onResponse(ApiResult<AddressObj> addressObjApiResult) {
                    addressReceiver.send(addressObjApiResult.getResult().cityAssemble);
                }
            });
        }

        @Override
        public void provideCountiesWith(int cityId, final AddressReceiver<County> addressReceiver) {
            getAddressList(cityId, 2, new Response.Listener<ApiResult<AddressObj>>() {
                @Override
                public void onResponse(ApiResult<AddressObj> addressObjApiResult) {
                    addressReceiver.send(addressObjApiResult.getResult().countyAssemble);
                }
            });
        }

        @Override
        public void provideStreetsWith(int countyId,
                                       final AddressReceiver<Street> addressReceiver) {
        }

    }
}
